"""
Trace utilities for parsing and working with trace IDs
"""

from flask import g, request
import re
from datetime import datetime

def parse_trace_id(trace_id):
    """
    Parse a trace ID to extract information about the request.
    
    Trace ID format: {timestamp}{pid}{random}{request_hash} (30 characters total)
    
    Args:
        trace_id (str): The trace ID to parse
        
    Returns:
        dict: Parsed information about the trace ID
    """
    if not trace_id or len(trace_id) != 30:
        return {
            'valid': False,
            'error': 'Invalid trace ID format'
        }
    
    try:
        timestamp_str = trace_id[:10]
        pid_str = trace_id[10:14]
        random_str = trace_id[14:24]
        hash_str = trace_id[24:]
        
        # Convert timestamp back to datetime
        timestamp = int(timestamp_str)
        dt = datetime.fromtimestamp(timestamp)
        
        return {
            'valid': True,
            'timestamp': timestamp,
            'datetime': dt.isoformat(),
            'pid': int(pid_str),
            'random': random_str,
            'hash': hash_str
        }
    except Exception as e:
        return {
            'valid': False,
            'error': f'Error parsing trace ID: {str(e)}'
        }

def get_request_info():
    """
    Get information about the current request for tracing purposes.
    
    Returns:
        dict: Information about the current request
    """
    trace_id = getattr(g, 'trace_id', None)
    trace_info = parse_trace_id(trace_id) if trace_id else None
    
    return {
        'trace_id': trace_id,
        'trace_info': trace_info,
        'method': request.method,
        'url': request.url,
        'remote_addr': request.remote_addr,
        'user_agent': request.headers.get('User-Agent', ''),
    }

def format_trace_log(message):
    """
    Format a log message with trace information.
    
    Args:
        message (str): The log message
        
    Returns:
        str: Formatted log message with trace information
    """
    trace_id = getattr(g, 'trace_id', 'NO_TRACE')
    return f"[{trace_id}] {message}"